<template>
  <div class="title">
    <div class="returns" @click="clickBack">
      <!-- <img src="@/assets/images/icon_back_arrow.png" alt="" /> -->
      <svg-icon class="icon-back-arrow" name="icon_back_arrow" :width="20" :height="20" />
      返回
    </div>
    <div v-if="route.query.state !== '草稿箱修改'" class="step">
      <div
        class="first"
        :class="stepValue * 1 === 1 ? 'step-active' : 'step-right'"
        @click="stepValue * 1 === 2 ? clickBack(2) : null"
      >
        <div class="yuan">1</div>
        <div class="step-name">{{ setUpList[0] }}</div>
      </div>
      <div
        class="first"
        :class="stepValue * 1 === 2 ? 'step-active' : 'step-left'"
        @click="stepValue * 1 === 1 ? onPublic('to') : null"
      >
        <div class="yuan">2</div>
        <div class="step-name">{{ setUpList[1] }}</div>
      </div>
    </div>
    <div>
      <div v-if="route.query.state === 'device'" class="next-button">
        <a-button class="save marg-right16" @click="clickBack(2)"> 上一步 </a-button>
        <a-button class="save wsave" @click="onPublic(3)">保存为草稿</a-button>
        <a-button v-if="positionTypes !== 2" class="save marg-left16" @click="onPublic(2)">
          定时发布
        </a-button>
        <a-button class="next marg-left16" @click="onPublic(1)"> 发布 </a-button>
      </div>
      <div v-else class="next-button">
        <a-button class="save wsave" @click="onPublic"> 保存为草稿 </a-button>
        <a-button
          v-if="route.query.state !== '草稿箱修改'"
          class="next marg-left16"
          @click="onPublic('to')"
        >
          下一步
        </a-button>
      </div>
    </div>
  </div>
  <div class="article-box">
    <div class="wang-box">
      <wang-editor
        :content="wangHtml"
        :title-values="titleValue"
        @getTitle="getTitle"
        @changeHtml="changeHtml"
      >
      </wang-editor>
    </div>

    <div class="upfile">
      <div class="fujian">
        <div>附件:<span class="up-title">（最多上传5个附件）</span></div>
        <div v-if="disabled" class="upload-title">
          <!-- <div>附件<span class="up-title">（最多上传5个附件）</span></div> -->
          <a-button :class="disabled ? 'up-buttons' : 'up-button'" :disabled="disabled">
            上传附件
          </a-button>
        </div>
        <Upload
          v-model:file-list="fileList"
          class="upfileBox"
          list-type="picture"
          action=""
          :multiple="true"
          :remove="deleteFiless"
          :custom-request="customRequest"
        >
          <a-button
            v-if="!disabled"
            :class="disabled ? 'up-buttons' : 'up-button'"
            :disabled="disabled"
          >
            上传附件
          </a-button>
        </Upload>
      </div>
      <div class="file-listss">
        <div v-for="item in fileList" :key="item.id" class="list-li">
          <!-- <template v-if="item.status !== 'error'"> -->
          <div class="left">
            <img :src="item.thumbUrl ? item.thumbUrl : ''" alt="" />
            <span class="left-name" @click="downloadURL(item.url, item.filename + item.filetype)"
              >{{ item.filename }}{{ item.filetype }}</span
            >
          </div>
          <div class="deletd" @click="deleteFiless(item)">
            <svg-icon name="icon_upload_delete_normal" :width="18" :height="18" />
            <span>删除</span>
          </div>
          <!-- </template> -->
        </div>
      </div>
    </div>
    <!-- 上传封面 -->
    <div class="cover-box">
      <div class="fengmian-name">
        <div class="tip">*</div>
        <div class="name">封面展示：</div>
        <div class="fengm-tip">（支持格式：JPG PNG JPEG ）</div>
      </div>
      <div class="enclosure-upload">
        <Upload
          v-if="!previewImage"
          action=""
          list-type="picture-card"
          :file-list="coverFileList"
          accept=".png, .jpeg, .jpg"
          :remove="deleteFiles"
          :custom-request="beforeUpload"
          @change="handleChange"
        >
          <!-- 封面列表 -->
          <div v-if="coverFileList.length < 1" class="ant-uploadss">
            <i class="ifont-wid-popup_icon_add" style="font-size: 24px"></i>
            <div class="ant-upload-text"> 点击上传 </div>
          </div>
        </Upload>
        <div v-else class="feng-mian">
          <img :src="previewImage" alt="" />
          <div class="bgss">
            <div class="delete-img">
              <img src="../../assets/images/bb.png" class="looks" @click="previewVisible = true" />
              <span class="hover-line"></span>
              <img src="../../assets/images/aa.png" @click="deleteFiles(previewImage)" />
            </div>
          </div>
        </div>
      </div>
      <div class="fengmian-name fengm-top">
        <div class="name">可选封面模板</div>
      </div>
      <div class="optional-list">
        <template v-for="(item, index) in defaultFengmian" :key="item.id">
          <div
            class="feng-mians"
            :class="fengmIndex === index ? 'feng-mians-active' : null"
            @click="defaultFengmianClick(item, index)"
          >
            <img :src="item" />
            <div class="active-icon">
              <div></div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
  <!-- 封面预览 -->
  <image-viewer
    v-model:visible="previewVisible"
    v-model:index="curImgIdx"
    :images="[previewImage]"
  />
  <!-- 发布设置弹窗 -->
  <my-dialog
    :dialog-state="publishDialog.visible"
    :dialog-title="publishDialog.title"
    :dialog-width="publishDialog.width"
    :icon-type="publishDialog.default"
    :but-status="publishDialog.butStatus"
    @handleCancel="publishDialogCancel"
    @handleOk="publishDialogOk"
  >
    <template #location>
      <div class="time">
        <div class="tips">*</div>
        <div>发布时长：</div>
        <a-range-picker
          v-model:value="publishTime"
          :disabled-time="disabledDateTime"
          format="YYYY-MM-DD HH:mm"
          show-time
          :disabled-date="disabledDate"
          :disabled="[true, permanentChecked ? true : false]"
          @change="selsectTime"
          @openChange="openChange"
          @ok="ok"
          @calendarChange="onCalendarChange"
        />
      </div>
      <div v-if="permanentChecked" class="time-slot">永久</div>
      <div v-else class="time-slot">{{ timeFn }}</div>
      <div class="permanent-switch">
        <div class="permanent">永久发布：</div>
        <a-switch v-model:checked="permanentChecked" @change="isForeverChange" />
      </div>
    </template>
  </my-dialog>
  <!-- 定时发布 -->
  <regular-release-dialog
    ref="regularReleaseChild"
    :regular-release="regularRelease.visible"
    :timing-data="timingData"
    :timing-state="timingState"
    @handleCancel="regularReleaseCancel"
    @handleOks="regularReleaseOk"
  ></regular-release-dialog>
  <!-- 发布提示弹窗 -->
  <my-dialog
    :dialog-state="publishTipsDialog.visible"
    :dialog-title="publishTipsDialog.title"
    :dialog-width="publishTipsDialog.width"
    :icon-type="publishTipsDialog.default"
    :but-status="publishTipsDialog.butStatus"
    :btn-title="publishTipsDialog.btnTitle"
    :determine-btn="publishTipsDialog.determineBtn"
    :other-btn="true"
    class="publish-tips-dialog"
    :btn-state="publishTipsDialog.btnState"
    @handleOther="publishTipsDialogOther"
    @handleCancel="publishTipsDialogCancel"
    @handleOk="publishTipsDialogOk"
  >
    <template #location>
      <div class="publish-scrollbar">
        <div class="content">
          <div class="content-left">
            <i :class="'icon-warring'" class="icon"></i>
            <span class="text">继续发布将覆盖正在发布信息的部分时段</span>
          </div>
          <div class="tipss"> （设备在所选时间内正在展示以下信息） </div>
        </div>
        <div class="off-line-equipment-list">
          <a-table :data-source="conflictDevice" :columns="columns">
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'equipmentName'">
                {{ record.equipmentName }}
              </template>
              <template v-else-if="column.dataIndex === 'model'">
                <div v-if="record.conflict === 0" class="equipment-choices">霸屏模式</div>
                <div v-else class="equipment-choicess">全屏模式</div>
              </template>
              <template v-else-if="column.dataIndex === 'releaseUserName'">
                {{ record.releaseUserName ? record.releaseUserName : '--' }}
              </template>
              <template v-else-if="column.dataIndex === 'releaseName'">
                {{ record.releaseName }}
              </template>
              <template v-else>
                <div class="equipment-choice" @click="choiceEquipment(index, record.equipmentId)"
                  >取消选择</div
                >
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </template>
  </my-dialog>
  <my-dialog
    :dialog-state="leaveDialog.visible"
    :dialog-title="leaveDialog.title"
    :dialog-width="leaveDialog.width"
    :icon-type="leaveDialog.warring"
    :determine-btn="true"
    :btn-title="leaveDialog.otherBtn"
    :btn-state="leaveDialog.determineBtn"
    :html="leaveDialog.html"
    :other-btn="true"
    :show-icon="true"
    :footer="true"
    :content-text="leaveDialog.content"
    @handleCancel="leaveDialog.visible = false"
    @handleOther="leaveDialogCancel"
    @handleOk="leaveDialogOk"
  ></my-dialog>
</template>
<script>
export default {
  name: 'article'
};
</script>
<script setup>
import ObsClient from 'esdk-obs-browserjs';
import wangEditor from '/src/components/layout/wangEditor';
import ImageViewer from '@/components/imageViewer';
import {
  deleteOBS,
  timeFns,
  handleCover,
  getThumbUrl,
  getEscapeUrl,
  defaultFengmian,
  downloadURL,
  columns
} from '../../util/OBSUpload';
import { Upload, Form, Message, Modal, Popover } from 'ant-design-vue';
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router';
import {
  saveInfoArticleDraft,
  getInfoArticle,
  saveInfoArticle,
  checkCollide,
  getAccessGet
} from '@/api/user';
import regularReleaseDialog from '@/components/regularReleaseDialog/index.vue'; // 定时发布弹窗
import moment from 'moment';
import dayjs from 'dayjs';
import MyDialog from '@/components/dialog/index.vue';
import { ref, watch, defineEmits, reactive, onMounted, defineExpose } from 'vue';
import { getFromRouteInfo } from '@/util/utils';

import store from '../../store';
const router = useRouter();
const route = useRoute();
let curImgIdx = ref(0);
// 弹窗相关
const leaveDialog = reactive({
  type: '',
  title: '温馨提示',
  html: 'html',
  content:
    '<div>有编辑的内容未发布，是否确认返回？</br>返回后将不会保存编辑内容，您可以先保存到草稿</div>',
  warring: 'warring',
  visible: false,
  otherBtn: '确认返回',
  determineBtn: '保存草稿后返回',
  width: '464px'
});
function clickBack(paramss) {
  // console.log(Object.keys(route.query).length === 0);
  // console.log(goBackState.value.length > 0);
  // 发布详情编辑, 重新发布  // 返回
  if (Object.keys(route.query).length === 0) {
    console.log(1);
    didagState();
  } else if (
    route.query.type === 'creatDraft' ||
    route.query.state === '编辑' ||
    route.query.state === '草稿箱修改' ||
    route.query.isBack === 'true'
  ) {
    console.log(22);
    didagState();
  } else {
    getApiParams('公共'); // 处理参数 发布参数
    console.log(params.value);
    store.commit('addCacheRoute', 'postMessage');
    store.commit('addCacheRoute', 'article');
    localStorage.setItem('informationData', JSON.stringify(params.value));
    // 区分本地和基座内部，封装返回上一页方法
    if (window.__MICRO_APP_ENVIRONMENT__) {
      router.push(getFromRouteInfo());
    } else {
      router.go(-1);
    }
  }
}
function didagState() {
  console.log(goBackState.value);
  if (goBackState.value.length > 0) {
    leaveDialog.visible = true;
  } else {
    getCloseData(); // 清除缓存等
    router.push({
      path: '/service/send'
    });
  }
}
function leaveDialogCancel() {
  leaveDialog.visible = false;
  getCloseData(); // 清除缓存等
  router.push({
    path: '/service/send'
  });
}
function getSaveDraft() {
  console.log('dsjgksdfj ');
  onPublic(0);
}
function leaveDialogOk() {
  leaveDialog.visible = false;
  onPublic(0);
}
let setUpList = ref(['内容编辑', '发布位置']);
let stepValue = ref(1); // 步骤调数值
let fengmIndex = ref();
function defaultFengmianClick(url, index) {
  fengmIndex.value = index;
  fengmianDeleteSatate.value = true;
  coverFileList.value = [];
  previewImage.value = url;
}
/** *********************************************************相关弹窗*****************************************************************/
const publishDialog = reactive({
  // 发布设置
  title: '发布设置',
  default: 'default',
  visible: false,
  butStatus: '确认发布',
  width: '545px'
});
// 发布提示弹窗
const publishTipsDialog = reactive({
  title: '发布提示',
  default: 'default',
  visible: false,
  determineBtn: true,
  btnState: '继续发布',
  btnTitle: '返回修改',
  width: '832px'
});
let conflictData = ref([]); // 冲突设备数据
// 冲突弹唱取消
function choiceEquipment(index, id) {
  conflictDevice.value.splice(index, 1);
  let data = [];
  JSON.parse(localStorage.getItem('postionData')).forEach(item => {
    if (item.positionId !== id) {
      data.push({ ...item });
    }
  });
  conflictData.value = conflictData.value.filter(items => {
    return items.positionId !== id;
  });
  if (conflictData.value.length === 0) {
    publishTipsDialog.determineBtn = false;
  } else {
    publishTipsDialog.determineBtn = true;
  }
}
// 发布提示确定
function publishTipsDialogOk() {
  publishTipsDialog.visible = false;
  params.value.positionBOList = conflictData.value;
  publishArticleApi(params.value); // 发布文章api
}
// 发布提示取消
function publishTipsDialogCancel() {
  publishTipsDialog.visible = false;
}
// 发布提示返回修改
function publishTipsDialogOther() {
  params.value.positionBOList = conflictData.value;
  publishTipsDialog.visible = false;
  let data = JSON.stringify(conflictData.value);
  localStorage.setItem('informationData', JSON.stringify(params.value));
  localStorage.setItem('postionData', data);
  router.push({
    path: '/position',
    query: {
      class: '文章',
      state: '设备',
      type: 'returnModify',
      pattern: route.query.patternState
    }
  });
}
/** *********************************************************数据区域*****************************************************************/
let Base64 = require('js-base64').Base64;
defineExpose({ getSaveDraft });
const emit = defineEmits(['getShopCode', 'goBack']);
const fileList = ref([]); // 附件
const coverFileList = ref([]); // 封面
const disabled = ref(false); // 上传是否禁用
const paramsData = ref(''); // 通过id获得的数据
const wangHtml = ref(''); // 富文本内容
const textData = ref('');
const previewVisible = ref(false);
const coverUploadState = ref(false); // 封面上传状态
const cfileUploadState = ref(false); // 文件上传状态
const previewImage = ref(''); // 封面Url
const titleValue = ref(''); // 内容标题
let defaultPreviewImage = ref([]); // 获取封面url 用于与监听值进行比较
let publishTime = ref([dayjs(moment().format('YYYY-MM-DD HH:mm')), '']); // 发布设置弹窗时间
let permanentChecked = ref(false); // 永久发布switch状态
let publishStartDate = ref(''); // 发布设置弹窗开始时间
let publishEndDate = ref(''); // 发布设置弹窗结束时间
let timeFn = ref('0天0时0秒');
let pattern = ref(0); // 霸屏值
let params = ref({
  infoBO: {
    pattern: 0, // ( 0普通模式 1霸屏模式)
    id: null,
    infoName: '', // 发布标题
    isDraft: 0, // 是否是草稿0非草稿  1草稿
    infoType: 3, // 0视频  1组图   2文档  3文章
    releaseFrequency: 0, // 发布频率 0每天 1每周
    thumbnailUrl: '', // 展示封面(缩略图url)
    isForever: 0, // 0非永久 1永久
    releaseOpportunityType: null, // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    validPeriodStart: '', // 有效期开始
    validPeriodStop: '' // 有效期结束
  },
  // 文章信息
  articleBO: {
    id: null,
    articeTitle: '', // 文章标题
    articleContent: '' // 文章内容标签
  },
  enclosureBOList: [] // 附件信息
});
/** *********************************************************方法区域*****************************************************************/
let positionTypes = ref(); // 应用平台 ==2
onMounted(() => {
  // 返回修改反显
  console.log('这-进入页面', route.query);
  // if (localStorage.getItem('informationData') && !route.query.id) {
  //   let informationData = JSON.parse(localStorage.getItem('informationData'));
  //   console.log('发布信息数据', JSON.parse(localStorage.getItem('informationData')));
  //   getDisplayData({
  //     articleVO: informationData.articleBO,
  //     enclosureVOList: informationData.enclosureBOList,
  //     infoVO: informationData.infoBO,
  //     oldPositionVOList: informationData.oldPositionBOList,
  //     positionVSSOList: informationData.positionBOList
  //   });
  // }
  if (route.query.state === 'device') {
    pattern.value = route.query.patternState;
    console.log('先设备后内容的设备信息', JSON.parse(localStorage.getItem('postionData')));
    positionTypes.value = JSON.parse(localStorage.getItem('postionData'))[0].positionType;
    setUpList.value = ['发布位置', '内容编辑'];
    stepValue.value = 2;
  }
  if (route.query.id) {
    editData();
  }
});
// 转换时间戳
function getTimeFormat(timeS) {
  let time = new Date(timeS).getTime(); // 除1000 是变成秒级的时间戳 不除就是毫秒级
  return time;
}
let fileLists = ref([]); // 附件展示
function getReturnData(data) {
  getDisplayData({
    articleVO: data.articleBO,
    enclosureVOList: data.enclosureBOList,
    infoVO: data.infoBO,
    oldPositionVOList: data.oldPositionBOList,
    positionVSSOList: data.positionBOList
  });
}
// 当日只能选择当前时间之后的时间点
const range = (start, end) => {
  const result = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};
const newS = ref('');
const currentTimes = ref('');
// 禁止当前时间之前的时间不可选
const disabledDateTime = (dates, partial) => {
  if (dates != null) {
    newS.value = moment(dates.$d).format('YYYY-MM-DD'); // 选择的时间
    currentTimes.value = moment(dates.$d).format('YYYY-MM-DD HH'); // 选择的时间
  }
  let currentTime = moment().format('YYYY-MM-DD'); // 当前时间
  let hours = moment().hours(); // 0~23
  let minutes = moment().minutes(); // 0~59
  let seconds = moment().seconds(); // 0~59
  if ((dates === null && partial === 'end') || newS.value === currentTime) {
    return {
      disabledHours: () => range(0, hours - 1),
      disabledMinutes: () => (currentTimes.value.slice(-2) <= hours ? range(0, minutes) : null),
      disabledSeconds: () => range(0, seconds - 1)
    };
  }
};
//  禁用当前时间之前的时间
function disabledDate(current) {
  return current && current < moment().subtract(1, 'days').endOf('day');
}
function ok(date) {
  timeFn.value = timeFns(
    getTimeFormat(publishStartDate.value),
    getTimeFormat(publishEndDate.value)
  );
  let newS = moment(publishTime.value[1].$d).format('YYYY-MM-DD HH:mm'); // 选择的时间
  let currentDate = moment().format('YYYY-MM-DD HH:mm');
  if (newS <= currentDate) {
    Message.error('结束时间不能小于等于开始时间,请重新选择结束时间');
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), null];
    publishEndDate.value = '';
    timeFn.value = '0天0时0秒';
  }
}
// 时间取消事件
function onCalendarChange() {
  timeFn.value = '0天0时0秒';
}
// 时间框事件
function openChange(e) {
  if (e) {
    publishTime.value = [
      dayjs(moment().format('YYYY-MM-DD HH:mm')),
      dayjs(moment().format('YYYY-MM-DD HH:mm'))
    ];
    publishStartDate.value = moment().format('YYYY-MM-DD HH:mm');
  } else {
    if (publishEndDate.value === '') {
      publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    } else {
      publishTime.value = [
        dayjs(moment().format('YYYY-MM-DD HH:mm')),
        dayjs(publishEndDate.value, 'YYYY-MM-DD HH:mm')
      ];
    }
  }
  if (publishEndDate.value !== '') {
    timeFn.value = timeFns(
      getTimeFormat(publishStartDate.value),
      getTimeFormat(publishEndDate.value)
    );
  }
}
function selsectTime(date, dateString) {
  publishStartDate.value = dateString[0];
  publishEndDate.value = dateString[1];
  disabledDateTime();
}
// 永久change
function isForeverChange() {
  if (permanentChecked.value) {
    publishTime.value = [
      dayjs(moment().format('YYYY-MM-DD HH:mm')),
      dayjs('9999-12-31 23:59', 'YYYY-MM-DD HH:mm')
    ];
  } else {
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    timeFn.value = '0天0时0秒';
  }
  publishEndDate.value = '';
}
// 发布设置取消按钮
function publishDialogCancel() {
  publishDialog.visible = false;
  permanentChecked.value = false;
  publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
}
let conflictDevice = ref([]); // 冲突设备list
// 发布设置确定
function publishDialogOk() {
  if (permanentChecked.value === false && publishEndDate.value === '') {
    Message.error('时长不能为空');
    return;
  }
  deviceConflictParams('发布'); // 发布设备冲突参数
  console.log(checkCollideParams.value, '定时发布参数');
  if (permanentChecked.value) {
    // 永久
    checkCollideParams.value.data.validPeriodStop = '9999-12-31 23:59:59';
    params.value.infoBO.validPeriodStop = '9999-12-31 23:59:59';
  } else {
    params.value.infoBO.validPeriodStop =
      publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value; // 有效期结束
  }
  getApiParams('发布'); // 处理参数 发布参数
  console.log('发布参数', params.value);
  if (publishTime.value[1] === '') {
    Message.error('时长不能为空');
    return;
  }
  if (params.value.positionBOList[0].positionType === 2) {
    publishArticleApi(params.value); // 发布文章api
  } else {
    getCheckCollideApi(); // 设备冲突接口
  }
  publishDialog.visible = false;
  permanentChecked.value = false;
  publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
}
// 定时发布状态
let regularRelease = ref({
  visible: false
});
// 定时发布取消按钮
function regularReleaseCancel() {
  regularRelease.value.visible = false;
}
// 点击定时发布
function regularReleaseOk(data) {
  console.log('阿斯顿哈师大', data);
  // releaseFrequency===0 天
  if (data.isForever === false) {
    if (data.validPeriodStart === '' || data.validPeriodStop === '') {
      Message.warning('请选择有效期限');
      return;
    }
    if (data.releaseFrequency === 0) {
      if (data.daySiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    } else {
      if (data.weekSiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    }
  } else {
    console.log(222);
    if (data.releaseFrequency === 0) {
      if (data.daySiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    } else {
      if (data.weekSiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    }
  }
  getApiParams('定时发布', data); // 发布参数
  deviceConflictParams('定时发布', data); // 设备冲突参数
  console.log(checkCollideParams.value, '定时发布参数1222');
  if (data.releaseFrequency === 0) {
    params.value.infoBO.daySiteBOList = data.daySiteBOList; // 按天发布 数组
  } else {
    params.value.infoBO.weekSiteBOList = data.weekSiteBOList; // 按周的定时发布 数组
  }
  regularRelease.value.visible = false;
  getCheckCollideApi('定时发布'); // 设备冲突接口
}
// 设备冲突接口
function getCheckCollideApi(type) {
  console.log(55555555, pattern.value, params.value.infoBO);
  checkCollide(checkCollideParams.value).then(res => {
    // 未返回数据 代表没有冲突设备
    if (res.data.data.records.length === 0) {
      publishArticleApi(params.value); // 发布文章api
    } else {
      // 打开设备冲突 弹窗
      if (type === '定时发布') {
        // conflictDevice.value = res.data.data.records; // 暂时不知道为啥注释8月前
        regularRelease.value.visible = false;
        publishTipsDialog.visible = true;
      } else {
        conflictDevice.value = res.data.data.records;
        publishTipsDialog.visible = true;
      }
    }
  });
}
// 设备冲突参数
let checkCollideParams = ref(''); // 设备冲突参数
function deviceConflictParams(type, data) {
  let equipmentIdList = []; // 设备id 集合
  JSON.parse(localStorage.getItem('postionData')).forEach(item => {
    equipmentIdList.push(item.positionId);
  });
  let releaseParamss = {
    current: 1,
    size: 10,
    data: {
      pattern: pattern.value, // ( 0普通模式 1霸屏模式);
      infoType: 3, // 1图像（视频+组图）   2文档  3文章
      validPeriodStart:
        type === '发布' ? moment().format('YYYY-MM-DD HH:mm:ss') : data.validPeriodStart,
      validPeriodStop:
        type === '发布'
          ? publishEndDate.value.length === 16
            ? publishEndDate.value + ':00'
            : publishEndDate.value
          : data.validPeriodStop,
      equipmentIdList: equipmentIdList, // 暂时设备只能单选
      opportunityType: type === '发布' ? 0 : 1,
      isForever: permanentChecked.value ? 1 : 0
    }
  };
  checkCollideParams.value = releaseParamss;
  if (type === '定时发布') {
    checkCollideParams.value.data.frequency = data.releaseFrequency; // 频率 0 天 1 周
    checkCollideParams.value.data.byWeekList =
      data.releaseFrequency === 1 ? data.weekSiteBOList : []; // 周
    checkCollideParams.value.data.byDayList = data.releaseFrequency === 0 ? data.daySiteBOList : []; // 天
  }
}
// 发布文章api
function publishArticleApi(params) {
  saveInfoArticle(params).then(res => {
    if (res.data.code === 200) {
      goHome('发布成功');
    }
  });
}
let oldPositionBOList = ref([]); // 位置信息
let isForever = ref(); // 永久状态
let releaseOpportunityType = ref(); //
let validPeriodStart = ref();
let validPeriodStop = ref();
let weekSiteVOList = ref([]); // 定时发布时间/周
let daySiteVOList = ref([]); // 定时发布时间/天
let createTime = ref('');
let defaultHtml = ref(''); // 默认获取后台html 用于比较
function editData() {
  getInfoArticle(route.query.id).then(res => {
    let data = res.data.data;
    getDisplayData(data); // 处理回显数据
  });
}
function getDisplayData(data) {
  console.log('getDisplayData-方法-2888222', data);
  paramsData.value = data; // 获得的所有数据集合
  coverFileList.value[0] = {
    url: getEscapeUrl(data.infoVO.thumbnailUrl, 'url'), // 封面file-list
    thumbUrl: getEscapeUrl(data.infoVO.thumbnailUrl, 'url')
  };
  if (defaultFengmian.indexOf(data.infoVO.thumbnailUrl) !== -1) {
    fengmIndex.value = defaultFengmian.indexOf(data.infoVO.thumbnailUrl); // 默认封面list
    previewImage.value = data.infoVO.thumbnailUrl; // 封面url
    defaultPreviewImage.value = data.infoVO.thumbnailUrl; // 用于监听比较封面
  } else {
    previewImage.value = getEscapeUrl(data.infoVO.thumbnailUrl, 'url'); // 封面url
    defaultPreviewImage.value = getEscapeUrl(data.infoVO.thumbnailUrl, 'url');
  }
  let fileListss = [];
  let thumbUrl;
  data.enclosureVOList.forEach(item => {
    thumbUrl = getThumbUrl(item);
    let url = getEscapeUrl(item.documentUrl, 'url');
    fileListss.push({
      filename: item.documentName, // 名字不带类型
      filetype: getEscapeUrl(item.documentUrl, 'type'), // 类型 .png
      status: 'done',
      name: getEscapeUrl(item.documentUrl, 'name') + getEscapeUrl(item.documentUrl, 'type'),
      thumbUrl: thumbUrl,
      urlTime: getEscapeUrl(item.documentUrl, 'assetsUrl'), // 获得倒数第三个斜杠/后面的 （assets/2022.../19212312....png）
      type: getEscapeUrl(item.documentUrl, 'type').slice(1),
      url: url
    });
  });
  fileList.value = fileListss; // 附件file-list
  fileLists.value = fileListss; // 附件处理过的list
  isForever.value = data.infoVO.isForever;
  pattern.value = data.infoVO.pattern;
  if (route.query.state === '编辑') {
    // console.log(data.positionVOList[0].positionType);
    positionTypes.value = data.positionVOList ? data.positionVOList[0].positionType : null; // 应用平台 ==2
  } else {
    positionTypes.value = data.positionVSSOList ? data.positionVSSOList[0].positionType : null;
  }
  titleValue.value = data.infoVO.infoName;
  setTimeout(() => {
    wangHtml.value = data.articleVO.articleContent;
    defaultHtml.value = data.articleVO.articleContent;
  }, 200);
  // console.log('富文本', data.articleVO.articleContent);
  createTime.value = data.infoVO.createTime; // 创建时间
  releaseOpportunityType.value = data.infoVO.releaseOpportunityType;
  validPeriodStart.value = data.infoVO.validPeriodStart;
  validPeriodStop.value = data.infoVO.validPeriodStop;
  oldPositionBOList.value = data.positionVOList; // 位置信息
  weekSiteVOList.value = data.weekSiteVOList; // 发布时间/周
  daySiteVOList.value = data.daySiteVOList; // 发布时间/天
}
let goBackState = ref([]); // 返回按钮状态是否弹弹窗
watch(previewImage, (newName, oldName) => {
  if (route.query.id) {
    // 监听封面previewImage字段是否打开离开弹窗
    if (newName === defaultPreviewImage.value) {
      emit('getShopCode', []); // 没有改变
      goBackState.value = [];
    } else {
      emit('getShopCode', [{ title: '发生改变1' }]);
      goBackState.value = [{ title: '发生改变1' }];
    }
  } else {
    // 默认进入页面 封面是第一个默认图， 所有是默认封面且没有更改过， 不需要弹窗
    if (
      newName ===
        'https://saas-information.obs.cn-east-3.myhuaweicloud.com/assets/img/gonggao1.png' &&
      !fengmianDeleteSatate.value
    ) {
      emit('getShopCode', []);
      goBackState.value = [];
    } else {
      emit('getShopCode', [{ title: '发生改变2' }]);
      goBackState.value = [{ title: '发生改变2' }];
    }
  }
});
watch(route, (newName, oldName) => {
  coverFileList.value = [];
  fileList.value = [];
  fileLists.value = [];
  textData.value = '';
  // wangHtml.value = '';
  // titleValue.value = ' ';
});
watch(wangHtml, (newName, oldName) => {
  console.log(newName);
  console.log(defaultHtml.value);
  if (route.query.id) {
    if (newName === defaultHtml.value) {
      emit('getShopCode', []);
      goBackState.value = [];
    } else {
      emit('getShopCode', '发生改变44');
      goBackState.value = '发生改变44';
    }
  } else {
    if (newName === '<p><br></p>') {
      emit('getShopCode', []);
      goBackState.value = [];
    } else {
      emit('getShopCode', newName);
      goBackState.value = newName;
    }
  }
});
watch(fileList, (newName, oldName) => {
  if (newName.length >= 5) {
    Message.error('最多上传5个附件!');
    disabled.value = true;
    console.log(newName.splice(5, 1));
    // fileList.value = newName.splice(5, 1);
    console.log(fileList.value);
  } else {
    disabled.value = false;
  }
  if (route.query.id) {
    if (newName === fileLists.value) {
      emit('getShopCode', []);
      goBackState.value = [];
    } else {
      emit('getShopCode', 'sssss');
      goBackState.value = 'sssss';
    }
  } else {
    if (newName.length > 0) {
      emit('getShopCode', newName);
      goBackState.value = newName;
    } else {
      emit('getShopCode', []);
      goBackState.value = [];
    }
  }
});
// 必选项
const checkPic = (rule, value) => {};
const fengmianDeleteSatate = ref(false); // 用户手动删除， 选择封面的状态（true, 有更改）
// 封面移除
function deleteFiles(file) {
  if (!route.query.id) {
    deleteOBS(file.urlTime);
  }
  fengmianDeleteSatate.value = true;
  coverUploadState.value = false;
  coverFileList.value = [];
  previewImage.value = '';
  fengmIndex.value = '';
}
function deleteFiless(file) {
  console.log(file);
  return new Promise(function (resolve, reject) {
    Modal.confirm({
      content: '确定要删除这个文件吗？',
      okButtonProps: { type: 'primary', style: 'color:#fff !important' },
      onOk() {
        fileList.value = fileList.value.filter(
          item => (item.originFileObj ? item.originFileObj.urlTime : item.urlTime) !== file.urlTime
        );
        fileLists.value = fileLists.value.filter(item => item.urlTime !== file.urlTime);

        if (!route.query.id) {
          deleteOBS(file.urlTime);
        }
        resolve(true);
        console.log(fileLists.value);
        console.log(fileList.value);
      },
      onCancel() {
        reject(false);
      }
    });
  });
}
// 上传封面
function beforeUpload(file) {
  uploadCheck(file, '封面', 5); // 上传类型校验
}
function uploadHandleChange(file, type) {
  console.log(file, fileList.value);
  let SourceFile = file.file;
  let fileDir = file.file.urlTime;
  uploadOBS(fileDir, SourceFile, type);
  coverUploadState.value = false;
  cfileUploadState.value = false;
}
// 封面Change
function handleChange({ fileList }) {
  coverFileList.value = fileList;
  coverFileList.value[0]['status'] = 'done';
}
// 上传附件
function customRequest(file) {
  uploadCheck(file, '附件', 10); // 上传校验
}
// 上传校验(file 文件数据,type类型 附件还是封面,limitationSize限制大小)
function uploadCheck(file, type, limitationSize) {
  let fileName = file.file.name;
  let index = file.file.name.lastIndexOf('.');
  let lastName = '.' + fileName.substring(index + 1); // 类型 .png
  let name = fileName.substring(0, fileName.lastIndexOf('.'));
  if (type === '封面') {
    if (
      lastName.toLowerCase() !== '.png' &&
      lastName.toLowerCase() !== '.jpg' &&
      lastName.toLowerCase() !== '.jpeg'
    ) {
      Message.error('只支持.png .jpg .jpeg格式');
      sliceFile(file, type); // 接取掉错误文件
    }
  }
  if (name.length > 50) {
    Message.error('附件名超出字符限制，请修改后重新上传!');
    sliceFile(file, type);
  } else if (file.file.size / 1024 / 1024 > limitationSize) {
    Message.error(`附件大小不能超过${limitationSize}M!`);
    sliceFile(file, type);
  } else if (file.file.size === 0) {
    Message.error('文件大小不能为0KB!');
    sliceFile(file, type);
  } else {
    file.file['status'] = 'done';
    file.file['filetype'] = lastName; // 类型 .png
    file.file['filename'] = name; // 单独名字
    file.file['time'] = new Date().getTime();
    console.log(9999, process.env);
    let urlTime =
      process.env.VUE_APP_WEB_URL_OBSBUCKET +
      '/assets/' +
      moment().format('YYYY-MM-DD') +
      '/' +
      file.file['time'] +
      '_tupian' +
      file.file.filetype;
    file.file['urlTime'] = urlTime;
    file.file['url'] = 'https://saas-information.obs.cn-east-3.myhuaweicloud.com/' + urlTime;
    if (type === '附件') {
      console.log(handleCover(file));
      file.file.thumbUrl = handleCover(file);
    } else {
      file.file['thumbUrl'] = 'https://saas-information.obs.cn-east-3.myhuaweicloud.com/' + urlTime;
    }
    console.log(file);
    uploadHandleChange(file, type === '封面' ? 'fengmian' : '附件');
  }
}
function sliceFile(file, type) {
  file.file['status'] = 'error';
  file['status'] = 'error';
  if (type === '附件') {
    fileList.value = fileList.value.filter(item => item?.originFileObj?.status !== 'error');
    return;
  } else {
    coverFileList.value = [];
    return;
  }
}
// 获取富文本标题
function getTitle(value) {
  if (route.query.id) {
    if (value === titleValue.value) {
      emit('getShopCode', []);
      goBackState.value = [];
    } else {
      emit('getShopCode', value);
      goBackState.value = value;
    }
  } else {
    emit('getShopCode', value);
    goBackState.value = value;
  }
  titleValue.value = value.replace(/\s*/g, '');
}
// 获取富文本内容
function changeHtml(params, imgLists) {
  // console.log('返回富文本', params);
  wangHtml.value = params;
  if (!route.query.id) {
    if (!fengmianDeleteSatate.value) {
      previewImage.value =
        imgLists.length !== 0
          ? imgLists[0].src
          : 'https://saas-information.obs.cn-east-3.myhuaweicloud.com/assets/img/gonggao1.png';
      coverFileList.value = [{}];
      if (
        previewImage.value ===
        'https://saas-information.obs.cn-east-3.myhuaweicloud.com/assets/img/gonggao1.png'
      ) {
        fengmIndex.value = 0;
      } else {
        fengmIndex.value = -1;
      }
    }
  }
}
const activeKey = ref('1');
const timingData = ref({});
let regularReleaseChild = ref(null);
const timingState = ref('');
// 共享事件
function onPublic(value) {
  if (titleValue.value === '') {
    Message.warning('标题不能为空');
    return;
  }
  if (wangHtml.value === '<p><br></p>') {
    Message.warning('内容不能为空');
    return;
  }
  if (!previewImage.value) {
    Message.warning('封面不能为空');
    return;
  }
  getApiParams('公共');
  if (value === 1) {
    publishDialog.visible = true;
  } else if (value === 2) {
    // if (route.query.returnData) {
    //   let datas = JSON.parse(route.query.returnData);
    //   if (datas.infoBO.daySiteBOList) {
    //     datas.daySiteVOList = datas.infoBO.daySiteBOList;
    //   }
    //   timingData.value = datas;
    //   timingState.value = '1';
    //   regularReleaseChild.value.getDatas(timingData.value, '1');
    // }
    regularRelease.value.visible = true;
  } else if (value === 'to') {
    console.log('to-下一步，新建下一步 与编辑下一步');
    params.value.infoBO.thumbnailUrl = previewImage.value;
    console.log(params.value.infoBO.thumbnailUrl);
    if (route.query.state === '编辑') {
      params.value.oldPositionBOList = oldPositionBOList.value;
      params.value.positionBOList = [];
      params.value.articleBO.id = paramsData.value.articleVO.id;
      params.value.infoBO.isForever = isForever.value;
      params.value.infoBO.releaseOpportunityType = releaseOpportunityType.value; // releaseOpportunityType null 0 1 2
      params.value.infoBO.validPeriodStart = validPeriodStart.value; // 开始时间
      params.value.infoBO.validPeriodStop = validPeriodStop.value; // 结束时间
      params.value.infoBO.id = route.query.id;
      params.value.infoBO.pushTime = createTime.value;
      params.value.weekSiteVOList = weekSiteVOList.value; // 发布时间-周
      params.value.daySiteVOList = daySiteVOList.value; // 发布时间-天
      console.log(params.value);
      let data = JSON.stringify(params.value);
      localStorage.setItem('postionData', data);
      localStorage.setItem('informationData', data);
      store.commit('addCacheRoute', 'postMessage');
      store.commit('addCacheRoute', 'postion');
      store.commit('addCacheRoute', 'article');
      router.push({
        path: '/position',
        query: {
          state: '编辑',
          releaseType: 4
        }
      });
    } else {
      console.log(params.value, '发布信息数据-也就是文章，图像数据');
      let datas = JSON.stringify(params.value);
      localStorage.setItem('informationData', datas);
      localStorage.setItem('postionData', localStorage.getItem('postionData'));
      store.commit('addCacheRoute', 'postMessage');
      store.commit('addCacheRoute', 'postion');
      store.commit('addCacheRoute', 'article');
      router.push({
        path: '/position',
        query: {
          id: route.query.state === '重新发布' ? route.query.id : null,
          state: route.query.state,
          releaseType: 4 //  区分发布文章还是图像设备的
        }
      });
    }
  } else {
    params.value.infoBO.isDraft = 1;
    params.value.infoBO.thumbnailUrl = previewImage.value;
    if (route.query.state === '编辑') {
      getApiParams('公共');
      saveDraftApi(params.value); // 保存草稿(编辑)
    } else if (route.query.state === '草稿箱修改') {
      params.value.infoBO.id = paramsData.value.infoVO.id;
      params.value.articleBO.id = paramsData.value.articleVO.id;
      saveDraftApi(params.value); // 保存草稿(修改)
    } else {
      console.log(55555, params.value);
      saveDraftApi(params.value); // 保存草稿(新建)
    }
  }
}
// 发布参数赋值
function getApiParams(type, data) {
  params.value.infoBO.pattern = pattern.value; // ( 0普通模式 1霸屏模式);
  params.value.infoBO.infoName = titleValue.value; // 标题
  params.value.articleBO.articeTitle = titleValue.value; // 标题
  params.value.articleBO.articleContent = wangHtml.value; // 富文本
  params.value.infoBO.thumbnailUrl = previewImage.value; // 封面
  if (type !== '公共') {
    conflictData.value = JSON.parse(localStorage.getItem('postionData'));
    params.value.positionBOList = JSON.parse(localStorage.getItem('postionData')); // 位置信息
  }
  if (type === '发布') {
    params.value.infoBO.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss'); // 有效期开始
    params.value.infoBO.isForever = permanentChecked.value ? 1 : 0; // 0非永久 1永久
    params.value.infoBO.releaseOpportunityType = 0; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
  } else if (type === '定时发布') {
    params.value.infoBO.validPeriodStart = data.validPeriodStart; // 有效期开始
    params.value.infoBO.validPeriodStop = data.validPeriodStop; // 有效期结束
    params.value.infoBO.isForever = data.isForever ? 1 : 0; // 0非永久 1永久
    params.value.infoBO.releaseOpportunityType = data.releaseFrequency === 0 ? 1 : 2; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    params.value.infoBO.releaseFrequency = data.releaseFrequency; // 发布频率 0每天 1每周
  } else if (type === '公共') {
    let enclosureBOList = getenClosureBOList();
    console.log(enclosureBOList);
    params.value.infoBO.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss');
    params.value.enclosureBOList = enclosureBOList;
    publishTipsDialog.determineBtn = true;
  }
}
// 保存草稿 接口
function saveDraftApi() {
  console.log(params.value);
  saveInfoArticleDraft(params.value).then(res => {
    if (res.data.code === 200) {
      goHome('保存草稿成功');
    }
  });
}
function goHome(data) {
  Message.success(data);
  getCloseData(); // 清除缓存等
  router.push({
    path: '/'
  });
}
function getCloseData() {
  store.commit('removeCacheRoute', 'postion'); // 存储keepalive数值
  store.commit('removeCacheRoute', 'postMessage');
  store.commit('removeCacheRoute', 'article');
  localStorage.removeItem('postionData'); // 清除位置信息
  localStorage.removeItem('informationData'); // 清除发布信息数据（图像， 文章）
}
// 处理附件
function getenClosureBOList() {
  let enclosureBOList = [];
  fileList.value.forEach(item => {
    enclosureBOList.push({
      documentUrl: 'https://saas-information.obs.cn-east-3.myhuaweicloud.com/' + item.urlTime, // 附件地址
      documentFormat: item.filetype.slice(1), // 附件格式 去除.
      documentName: item.filename // 附件名称
    });
  });
  return enclosureBOList;
}
function uploadOBS(fileDir, SourceFile, type) {
  let keys;
  let ids;
  getAccessGet().then(res => {
    ids = res.data.data.Accesskeyid;
    keys = res.data.data.Policy;
  });
  let obsClient = new ObsClient({
    access_key_id: ids,
    secret_access_key: keys,
    server: 'https://obs.cn-east-3.myhuaweicloud.com'
  });
  obsClient.putObject(
    {
      Bucket: 'saas-information',
      Key: fileDir,
      SourceFile: SourceFile // 文件
    },
    function (err, result) {
      if (err) {
        console.log('上传失败');
      } else {
        console.log('上传成功');
        if (type === 'fengmian') previewImage.value = coverFileList.value[0].originFileObj.thumbUrl;
        if (type === '附件') {
          let list = [];
          console.log(fileList.value);
          fileList.value.forEach(item => {
            // list.push({ ...item.originFileObj });
            if (item.originFileObj) {
              item.filename = item.originFileObj.filename;
              item.filetype = item.originFileObj.filetype;
              item.urlTime = item.originFileObj.urlTime;
              item.thumbUrl = item.originFileObj.thumbUrl;
              item.status = item.originFileObj.status;
            }
          });
          // fileLists.value = list;
        }
        console.log(fileList.value, '处理');
      }
    }
  );
}
</script>
<style lang="less" scoped>
@import './index.less';
@import '../imgAndVideo/header.less';
</style>
